package site.guns.controller;

import java.io.IOException;
import java.io.InputStream;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import site.guns.couchdb.GunsDb;
import site.guns.domain.GunInfo;
import site.guns.form.GunInfoForm;

import com.n1global.acc.CouchDbDocIdAndRev;

@Controller
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private GunsDb gunsDb;

    @RequestMapping(value = "/new", method = RequestMethod.GET)
    public String newGun(@SuppressWarnings("unused") @ModelAttribute("form") GunInfoForm form) {
        return "/admin";
    }

    @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
    public String edit(@PathVariable String id, Model model) {
        GunInfoForm form = new GunInfoForm();

        GunInfo gunInfo = gunsDb.get(id);
        BeanUtils.copyProperties(gunInfo, form);

        model.addAttribute("form", form);

        return "/admin";
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String post(GunInfoForm form) throws IOException {
        GunInfo gi = (GunInfo) (form.getDocId().isEmpty() ? new GunInfo() : gunsDb.get(form.getDocId()));

        BeanUtils.copyProperties(form, gi);

        if (!form.getFile().isEmpty()) {
            try (InputStream in = form.getFile().getInputStream()) {
              gi.setImage(in);
            }
        }

        gunsDb.saveOrUpdate(gi);

        return "redirect:/";
    }

    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public String delete(String id, String rev) {
        gunsDb.delete(new CouchDbDocIdAndRev(id, rev));

        return "/main";
    }
}
